//
//  UITextFieldExample.swift
//  SwiftCode
//
//  Created by yuhus on 2024/5/11.
//

import Foundation
import UIKit
import RxSwift

class UITextFieldExample: UIViewController {
  private let bag = DisposeBag()
  
  override func viewDidLoad() {
    super.viewDidLoad()
    view.backgroundColor = .systemBackground
    
    navigationItem.rightBarButtonItem = .init(title: "复制", style: .plain, target: self, action: #selector(onCopy))
    
    view.addSubview(textField)
    textField.snp.makeConstraints { make in
      make.top.equalTo(view.safeAreaLayoutGuide)
      make.leading.trailing.equalToSuperview().inset(16)
    }
    
    bindData()
  }
  
  func bindData() {
    textField.rx.limitLength(10).disposed(by: bag)
    
    Observable.just("我是初始化名称")
      .bind(to: textField.rx.text)
      .disposed(by: bag)
    
    textField.rx.text.orEmpty
      .debug()
      .map { String($0.prefix(10)) }
      .bind(to: textField.rx.text)
      .disposed(by: bag)
  }
  
  @objc func onCopy() {
//    UIPasteboard.general.string = "如果没有标记的文本，属性的值为nil。"
    UIPasteboard.general.string = "123456😃😄💕😄😃"
  }
  
  lazy var textField: UITextField = {
    let textField = UITextField()
    textField.font = .poppinsFont(ofSize: 15)
    textField.clearButtonMode = .whileEditing
    textField.borderStyle = .roundedRect
    textField.returnKeyType = .done
    return textField
  }()
}

extension Reactive where Base: UITextField {
  /// 限制输入框输入长度
  /// - Parameter length: 限制的长度
  /// - Returns: 销毁者
  public func limitLength(_ length: Int) -> Disposable {
    return controlEvent(.editingChanged)
      .subscribe(onNext: { [weak base = self.base] in
        if base?.markedTextRange == nil,
           let text = base?.text, text.count > length {
          let endIndex = text.index(text.startIndex, offsetBy: length)
          base?.text = String(text[..<endIndex])
        }
        base?.undoManager?.removeAllActions()
      })
  }
}
